<template>
 <div>
   <p class="f16">商品管理</p>
   <div class="mt-10">
     <Button @click="openModal" type="primary" class="mr-10"><Icon type="md-add" />新增商品</Button>
     <Button @click="batchUpdateSellStatus(0)" type="error" class="mr-10"><Icon type="md-arrow-down" />下架商品</Button>
     <Button @click="batchUpdateSellStatus(1)" type="success"><Icon type="md-arrow-up" />上架商品</Button>
   </div>
   <div class="mt-20 flex flex-column align-center justify-center w-100">
     <Table
        :columns="columns"
        :data="tableDate"
        @on-select="onSelect"
        @on-select-all="onSelectAll"
        @on-select-cancel="onSelect"
        @on-select-all-cancel="onSelectAll"
        ></Table>
        <Page 
          :total="page.total"
          :current="page.pageNum"
          :page-size="page.pageSize"
          show-sizer
          @on-change="pageChange"
          @on-page-size-change="pageSizeChange"
          class="my-20">
        </Page>
   </div>
   <Modal
      v-model="isShow"
      :title="content"
      @on-ok="onOk"
      @on-cancel="onCancel">
      <Form ref="addCommodityList" :model="addCommodityList" :rules="ruleAddCommodityList" :label-width="80">
        <FormItem label="商品分类" prop="categoryId">
          <Select v-model="addCommodityList.categoryId" filterable>
            <Option-group :label="item.name" v-for="item in categoryLists" :key="item.id">
              <Option v-for="ele in item.childCategory" :value="ele.id" :key="ele.id" >{{ ele.name }}</Option>
            </Option-group>
          </Select>
        </FormItem>
        <FormItem label="商品名称" prop="name">
          <Input type="text" v-model="addCommodityList.name" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="商品简介" prop="detail">
          <Input type="textarea" v-model="addCommodityList.detail" placeholder="请输入商品简介" />
        </FormItem>
        <FormItem label="商品库存" prop="stock">
          <Input type="number" v-model="addCommodityList.stock" placeholder="请输入商品库存" />
        </FormItem>
        <FormItem label="商品售价" prop="price">
          <Input type="number" v-model="addCommodityList.price" placeholder="请输入商品售价" />
        </FormItem>
        <FormItem label="商品图片">
          <template>
            <Upload
              ref="upload"
              :show-upload-list="showUploadList"
              :default-file-list="defaultList"
              :max-size="2048"
              :data="imgsData"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccess"
              action="/api/admin/upload/file">
              <Button type="default" icon="ios-cloud-upload-outline">上传图片</Button>
            </Upload>
            <div class="w-100 mt-20" style="min-height:120px" v-show="uploadList.length">
              <div class="demo-upload-list" v-for="(item, index) in uploadList" :key='item.id'>
                <img :src="item.url" style="width:100px;">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(item, index)"></Icon>
                </div>
              </div>
            </div>
            <Modal
              :title="imgShow.imgDesc"
              v-model="visible">
              <img :src="imgShow.url" class="w-100 relative min-400">
              <div class="absolute flex justify-between align-center modal-big-img">
                <Icon type="ios-arrow-dropleft-circle" @click="OnOnePiece(imgShow.url)"></Icon>
                <Icon type="ios-arrow-dropright-circle" @click="nextPage(imgShow.url)"></Icon>
              </div>
            </Modal>
          </template>
        </FormItem>
      </Form>
   </Modal>
 </div>
</template>
<script>
import { productList, categoryList, batchUpdateSellStatus, productAdd, productUpdate, productDelete } from 'api'
export default {
  data () {
    return {
      isShow: false,
      // baseURL: 'http://192.168.3.51:8084/', // 地址
      baseURL: 'http://127.0.0.1:8084/', // 地址
      columns: [
        {
          type: 'selection',
          align: 'center',
          width: '60'
        },
        {
          key: 'id',
          title: '商品编号',
          align: 'center'
        },
        {
          key: 'name',
          title: '商品名称',
          align: 'center'
        },
        {
          key: 'detail',
          title: '商品简介',
          align: 'center',
          width: '320px'
        },
        {
          key: 'image',
          title: '商品图片',
          align: 'center',
          render: (h,params) => {
            return <div>
            <img style="width:80px;height:80px" src={this.baseURL + params.row.image} />
            </div>
          }
        },
        {
          key: 'stock',
          title: '商品库存',
          align: 'center'
        },
        {
          key: 'price',
          title: '商品售价',
          align: 'center'
        },
        {
          key: 'status',
          title: '商品状态',
          align: 'center',
          render: (h,params) => {
            return <div>{params.row.status === 1? '已上架': '已下架'} </div>
          }
        },
        {
          key: 'createTime',
          title: '创建时间',
          align: 'center',
          render: (h,params) => {
            return <div>
            { this.format(params.row.createTime, 'yyyy年MM月dd日hh时mm分ss秒') }
            </div>
          }
        },
        {
          title: '操作',
          align: 'center',
          render: (h,params) => {
            return <div>
              <Button onClick={this.redact.bind(this, params.row)}>
              <Icon type="md-create" />编辑</Button>
              <Button type="error" onClick={this.delete.bind(this, params.row)}>
              <Icon type="md-trash" />删除</Button>
            </div>
          }
        },
      ],
      tableDate: [],
      addCommodityList: {}, // 新增数据
      content: '新增商品',
      showUploadList: true, // 显示上传的图片列表
      defaultList: [],
      imgShow: {}, // 图片展示
      visible: false, // 放大框
      imgsData: {}, // 图片上传数据
      uploadList: [],
      defaultimg: true,
      ruleAddCommodityList: {
        categoryId: [
          {required: true, message: '请选择商品类别'}
        ],
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        detail: [
          {required: true, message: '请选择商品简介', trigger: 'blur'}
        ],
        stock: [
          {required: true, message: '请选择商品库存', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请选择商品售价', trigger: 'blur'}
        ],
      }, // 正则
      categoryLists: [], // 分类
      upDownList: [], // 上下架列
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 10,
      }
    }
  },
  created() {
    this.productList()
    this.categoryList()
  },
  mounted() {

  },
  methods: {
    // 商品列表
    productList() {
      productList(this.page).then(res => {
        this.tableDate = res.list
        this.page.pageNum = res.pageNum
        this.page.pageSize = res.pageSize
        this.page.total = res.total
      })
    },
    // 商品分类
    categoryList() {
      categoryList().then(res => {
        this.categoryLists = res
      })
    },
    // 添加商品
    openModal() {
      this.isShow = true
      this.content = '新增商品'
    },
 
    // 上下架
    batchUpdateSellStatus(sellStatus) {
      let obj = {
        ids: this.upDownList,
        sellStatus: sellStatus
      }
      if (!this.upDownList.length) {
        this.$Message.error('请选择商品')
        return
      }
      batchUpdateSellStatus(obj).then(res => {
        if (sellStatus) {
          this.$Message.success('上架成功!')
        } else {
          this.$Message.success('下架成功!')
        }
        this.productList()
      })
    },
    // 单选事件
    onSelect(item) {
      this.upDownList = []
      item.forEach(ele => {
        this.upDownList.push(ele.id)
      })
    },
    // 全选事件
    onSelectAll (item) {
      this.upDownList = []
      item.forEach(ele => {
        this.upDownList.push(ele.id)
      })
    },
    // 查看大图
    handleView (name) {
      this.imgShow = name
      this.visible = true
    },
    // 上一张
    OnOnePiece (url) {
      if (this.uploadList.length > 1) {
        for (let i = 0; i < this.uploadList.length; i++) {
          if (this.uploadList[i].url === url) {
            if (i >= 1) {
              this.imgShow = this.uploadList[i - 1]
            } else {
              this.imgShow = this.uploadList[this.uploadList.length - 1]
            }
          }
        }
      }
    },
    // 下一张
    nextPage (url) {
      if (this.uploadList.length > 1) {
        for (let i = 0; i < this.uploadList.length; i++) {
          if (this.uploadList[i].url === url) {
            if (i < this.uploadList.length - 1) {
              this.imgShow = this.uploadList[i + 1]
            } else {
              this.imgShow = this.uploadList[0]
            }
          }
        }
      }
    },
    // 从 upload 实例删除数据
    handleRemove (item, index) {
      this.uploadList.splice(index, 1)
    },
    // 成功回调
    handleSuccess (res, file) {
      const row = {
        imgDesc: file.name,
        id: file.uid,
        url: res.data
      }
      this.uploadList.push(row)
      this.addCommodityList.image = 'images/' + file.name
      console.log(this.addCommodityList)
      this.defaultimg = false
      setTimeout(() => {
        this.showUploadList = false
        this.defaultList = []
      }, 1000)
    },
    // 文件后缀错误
    handleFormatError (file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      })
    },
    // 文件大小错误
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      })
    },
    // 图片文件上传之前
    handleBeforeUpload (data) {
      if (!this.showUploadList) this.showUploadList = true
      const check = this.uploadList.length < 10
      if (!check) {
        this.$Notice.warning({
          title: '最多只能上传 10 张图片。'
        })
      }
      return check
    },
    // 添加修改商品
    onOk() {
      if(this.addCommodityList.hasOwnProperty('id')) {
        productUpdate(this.addCommodityList).then(res => {
          this.productList()
        })
      } else {
        productAdd(this.addCommodityList).then(res => {
          this.productList()
        })
      }
    },
    // 取消
    onCancel() {
      this.addCommodityList = {}
    },
    // 页码
    pageChange(pageNum) {
      this.page.pageNum = pageNum
      this.productList()
    },
    // 页数
    pageSizeChange(pageSize) {
      this.page.pageSize = pageSize
      this.productList()
    },
    // 编辑
    redact(data) {
      this.uploadList = []
      this.isShow = true
      this.content = '编辑商品'
      this.addCommodityList = data
      let img = this.baseURL + data.image
      this.uploadList.push({
        imgDesc: data.image,
        url: img
      })
    },
    // 删除
    delete(data) {
      this.$Modal.confirm({
        title: '提示信息',
        content: `确认删除<span style="color:red">${data.name}</span>商品吗?`,
        onOk: () => {
          productDelete(data.id).then(res => {
            this.$Message.success('删除成功');
            this.productList()
          })
        },
      })
    },

    format(date, fmt) {
      date = new Date(date)
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    }
  },
}
</script>
<style lang='less' scoped>
.fc-red{
  color: red;
}
.demo-upload-list{
  display: inline-block;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  border: 1px solid transparent;
  border-radius: 5px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0,0,0,.2);
  margin-right: 4px;
}
.min-400{
  min-height: 400px;
}
.demo-upload-list img{
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover{
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
  display: block;
}
.demo-upload-list-cover i{
  color: #fff;
  font-size: 30px;
  cursor: pointer;
  margin: 0 6px;
}
.modal-big-img {
  top: 50%;
  left: 0;
  width: 100%;
  height: 30px;
  margin-top: -15px;
  padding: 0 16px;
}
.modal-big-img i {
  color: rgb(148, 147, 147);
  font-size: 30px;
  cursor: pointer;
  line-height: 30px;
  text-align: center;
}
</style>